package com.joyintech.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;

import com.joyintech.config.McpException;
import com.joyintech.dao.FileMapper;
import com.joyintech.model.FileUrl;
import com.joyintech.util.IDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

/**
 * @author LENOVO
 */
@Slf4j
@Service
public class FileService {

    @Value("${web.upload-path}")
    private String uploadPath;


    @Resource
    FileMapper fileMapper;

    public FileUrl save(MultipartFile file, String project) throws IOException {

        // 获取MD5
        String formattedDate = DateUtil.format(new Date(), "yyyy/MM/dd");
        String format = FileUtil.normalize(formattedDate);

        File folder = new File(uploadPath + "image1" + File.separator + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名, 避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        // 文件保存
        file.transferTo(new File(folder, newName));
        // 添加日志输出
        log.info("文件保存成功：" + folder.getPath() + File.separator + newName);

//        String filePath = File.separator +"api"+File.separator + "image1"+ File.separator + format + File.separator + newName;
        String filePath = File.separator + "image1"+ File.separator + format + File.separator + newName;

        FileUrl fileUrl = new FileUrl();
        fileUrl.setId(IDGenerator.generate());
        fileUrl.setFileUrl(filePath);
        fileUrl.setProject(project);
        fileUrl.setState("1");
        fileUrl.setCreateTime(new Date());
        fileUrl.setFileName(file.getOriginalFilename());
        fileUrl.setRealPath(filePath);
        fileMapper.insert(fileUrl);
        return fileUrl;
    }

    public static void main(String[] args) {
        String formattedDate = DateUtil.format(new Date(), "yyyy/MM/dd");
        System.out.println(formattedDate);
        String format = FileUtil.normalize(formattedDate);
        System.out.println(format);
    }

    public void downloadFile(Integer id, HttpServletResponse response) throws Exception {

    }

    private String getFileMd5HashCode(InputStream fis) {
        try {
            // 拿到一个MD5转换器,如果想使用SHA-1或SHA-256，则传入SHA-1,SHA-256
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 分多次将一个文件读入，对于大型文件而言，比较推荐这种方式，占用内存比较少。
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md.update(buffer, 0, length);
            }
            fis.close();
            // 转换并返回包含16个元素字节数组,返回数值范围为-128到127
            byte[] md5Bytes = md.digest();
            BigInteger bigInt = new BigInteger(1, md5Bytes);// 1代表绝对值
            return bigInt.toString(16);// 转换为16进制
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteFile(Integer id) throws Exception {
        FileUrl fileUrl = fileMapper.selectById(id);
        fileUrl.setState("0");
        fileMapper.updateById(fileUrl);

    }

    public String getImageUrl(int id) {
        FileUrl fileUrl = fileMapper.selectById(id);
        if (fileUrl == null) {
            throw new McpException("图片不存在");
        }
        return fileUrl.getFileUrl();
    }
}
